package logic;

import java.nio.ByteBuffer;
import java.util.Arrays;

import logic.exceptions.invalidSizeOfArrayException;

public class DNSMessage {
	private static short maxID=0;
	private static int maxInfLength=498;
	
	private short ID=0;
	private byte[] flags={1,0};
	private short qQaunt=0;
	private short aQaunt=0;
	private short nsQaunt=0;
	private short addQaunt=0;
	private byte[] qRecord={};
	private byte[] aRecord={};
	private byte[] authRecord={};
	private byte[] addRecord={};
	
	private long createTime=0;
	private String domain = Constants.NS_SERVER;
	private long randomPart = 0;
	private int length=0;
	
	private DNSMessage(){}
	
	public byte[] toByteArray(){
		byte[] result = new byte[length];
		ByteBuffer buffer = ByteBuffer.allocate(2);
		byte[] tmp = buffer.putShort(ID).array();
		result[0]=tmp[0];
		result[1]=tmp[1];
		for (int i=0;i<2;i++){
			result[i+2]=flags[i];
		}
		tmp = buffer.putShort(qQaunt).array();
		result[4]=tmp[0];
		result[5]=tmp[1];
		tmp = buffer.putShort(aQaunt).array();
		result[6]=tmp[0];
		result[7]=tmp[1];
		tmp = buffer.putShort(nsQaunt).array();
		result[8]=tmp[0];
		result[9]=tmp[1];
		tmp = buffer.putShort(addQaunt).array();
		result[10]=tmp[0];
		result[11]=tmp[1];
		for (int i=0;i<qRecord.length;i++){
			result[i+12]=qRecord[i];
		}
		for (int i=0;i<aRecord.length;i++){
			result[i+12+qRecord.length]=aRecord[i];
		}
		for (int i=0;i<authRecord.length;i++){
			result[i+12+qRecord.length+aRecord.length]=authRecord[i];
		}
		for (int i=0;i<addRecord.length;i++){
			result[i+12+qRecord.length+aRecord.length+authRecord.length]=addRecord[i];
		}
		return result;
	}
	
	public static DNSMessage generateRequest(byte[] infForSend) throws invalidSizeOfArrayException {
		DNSMessage result= new DNSMessage();
		result.ID=maxID++;
		result.createTime=System.currentTimeMillis();
		result.qQaunt=1;
		if (infForSend.length>maxInfLength){
			throw new invalidSizeOfArrayException();
		}
		result.length=Math.max(infForSend.length, maxInfLength);
		result.qRecord=Arrays.copyOf(infForSend, result.length);		
		return result;
	}
	
	public byte[] formatRecord(byte[] rec){
		byte[] result = new byte[rec.length];		
		return result;
	}
}
